package com.example.zuo.mysuperwidgetdemo.utils;

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zuo.mysuperwidgetdemo.R;


/**
 * Created by zuo on 2016/10/13.
 */
public class ToastUtils {
    private static String oldMsg;
    protected static Toast mToast = null;
    private static long oneTime = 0;
    private static long twoTime = 0;
    /**
     * 带图片的吐司
     */
    public static void toastWithPic(Context context, String text, int resId) {
        toast(context, text, Toast.LENGTH_SHORT, resId);
    }

    /**
     * 如果连续多次调用此方法，吐司显示时长不会累积，而是以最后一次调用时的时间为起始时间
     */
    public static void toast(Context context, String text, int duration, int resId) {
        if (mToast == null) {
            mToast = Toast.makeText(context.getApplicationContext(), text, duration);//这里要用ApplicationContext，否则可能会内存泄漏
        } else {
            mToast.setText(text);
            mToast.setDuration(duration);
        }
        LinearLayout toastView = (LinearLayout) mToast.getView();//吐司的布局是一个LinearLayout
        int viewCount = toastView.getChildCount();
        if (resId == -1) {
            if (viewCount > 1) {//如果有超过1个的子view，说明里面有一个图片
                toastView.removeViewAt(0);//移除掉图片
            }
        } else {
            if (viewCount <= 1) {//如果有少于2个的子view，说明里面没有图片
                ImageView imageCodeProject = new ImageView(context.getApplicationContext());
                imageCodeProject.setImageResource(resId);
                toastView.addView(imageCodeProject, 0);//index the position at which to add the child
            }
        }
        mToast.show();
    }

    private static Toast mCustomToast;
private static TextView textView;
    /**
     * 完全自定义的吐司
     */
    public static void showCustomToast(Context context, String message) {
        if (mCustomToast == null) {
            View layout = LayoutInflater.from(context).inflate(R.layout.toast_layout, null);

            textView=(TextView) layout.findViewById(R.id.tvTitleToast);
            textView .setText(message);

            mCustomToast = new Toast(context.getApplicationContext());
            mCustomToast.setView(layout);
            mCustomToast.setGravity(Gravity.CENTER,0,0);
            mCustomToast.setDuration(Toast.LENGTH_SHORT);
            mCustomToast.show();
            oneTime = System.currentTimeMillis();
        }else{
            twoTime = System.currentTimeMillis();
            if (message.equals(oldMsg)) {
                if (twoTime - oneTime > Toast.LENGTH_SHORT) {
                    mCustomToast.show();
                }
            } else {
                oldMsg = message;
                textView .setText(message);
                mCustomToast.show();
            }
        }
        oneTime = twoTime;
    }
}